package com.yc.web.servlets;

import com.yc.web.model.JsonModel;
import com.yc.bean.Shoes;
import com.yc.bean.User;
import com.yc.dao.RedisHelper;
import redis.clients.jedis.Jedis;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.yc.utils.YcConstants.*;

@WebServlet(name = "historicalServlet",value = "/historical.action")
public class historicalServlet extends BaseServlet{
    //数据埋点：将历史记录存入redis中存储
    protected void traceBrowseFood(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JsonModel jm = new JsonModel();
        String sid = req.getParameter("sid");
        HttpSession session = req.getSession();
        if (session.getAttribute(USER)==null){
            jm.setCode(-1);
            jm.setError("未登录用户不记录足迹");
            super.writeJson(jm,resp);
            return;
        }
        User user = (User) session.getAttribute(USER);
        int userid = user.getUserid();

        Date d = new Date();

        Jedis jedis = RedisHelper.getRedisInstance();
        //先检查  此键的值  的长度 ，如超过5个，侧删除4以后的数据
        long length = jedis.zcard(userid+REDIS_VISITED);
        if (length>=5){
            //rem表示按降序排列   删除第一个数据
            jedis.zremrangeByRank(userid+REDIS_VISITED,0,0);
        }
        //再存
        jedis.zadd(userid+REDIS_VISITED,d.getTime(),sid);
        jm.setCode(1);
        super.writeJson(jm,resp);
    }
    //获取redis中存储的历史记录
    protected void getHistory(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JsonModel jm = new JsonModel();
        String fid = req.getParameter("fid");
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute(USER);
        int userid = user.getUserid();

        Date d = new Date();

        Jedis jedis = RedisHelper.getRedisInstance();
        //访问获取最近的5个访问记录     zrevrange:逆序
//        Set<String> visitedFoodIds = jedis.zrevrange( userid+REDIS_VISITED,0,4);
        Set<String> visitedFoodIds = jedis.zrevrange(userid + REDIS_VISITED, 0, 4)
                .stream()
                .collect(Collectors.toSet());
        if (visitedFoodIds==null || visitedFoodIds.size()<=0){
            jm.setCode(0);
            super.writeJson(jm,resp);
            return;
        }
        //采用   sql中的 in 拼接多个商品的查询 ，减少多个sql语句操作
        StringBuffer sqlbuffer = new StringBuffer("SELECT Shoes.sid,sbrand,sgender,ssize,scolor,style,sprice,sdescription,sstockquantity,photourl,ismain " +
                "FROM Shoes JOIN ShoePhotos ON Shoes.sid = ShoePhotos.sid JOIN ShoeStyle ON Shoes.sstyle=ShoeStyle.styleid " +
                "WHERE ismain='true' and Shoes.sid in( ");
        for (String id : visitedFoodIds){
            sqlbuffer.append(" ?,");
        }
        String sql = sqlbuffer.toString();
        //去掉最后多的 ,  号
        sql=sql.substring(0 ,sql.length()-1);
        sql=sql+")";
//        System.out.println("执行的sql语句为："+sql);   //将sql语句拼装后的语句打印出来
//        System.out.println("visitedFoodIds.toArray()集合为:"+visitedFoodIds.toArray());
        List<Shoes> list = db.select(Shoes.class,sql,visitedFoodIds.toArray());
        jm.setCode(1);
        jm.setObj(list);
        super.writeJson(jm,resp);
    }
}
